<!-- 编辑弹窗 -->
<template>
    <ele-modal
      inner
      fullscreen
      :movable="false"
      :visible="visible"
      :close-on-click-modal="true"
      :before-close="handleClose"
      custom-class="ele-dialog-form"
      :title="isUpdate ? '修改盘点信息' : '添加盘点信息'"
      @update:visible="updateVisible" 
    >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px" >
      <el-card  >  
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >基础信息</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div v-show="form.checkNo!='' && form.checkNo!=null" style="width: 30%;color:var(--color-primary)" >盘点单号:{{ form.checkNo }}</div>
          </div>
        </div>      
        <el-row :gutter="24">
          <el-col :md="6" :sm="24" >
            <el-form-item label="制单日期:"  prop="createDate">
              <el-date-picker v-model="form.createDate" type="date" placeholder="请输入制单日期" format="yyyy-MM-dd" value-format="yyyy-MM-dd" style="width:100%"  />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="制单人:" prop="createUser">
              <el-select  v-model="form.createUser" filterable placeholder="请选择制单人" style="width:100%"  >
                <el-option  v-for="item in accountDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="盘点仓库:" prop="wareHouseId">
              <el-select  v-model="form.wareHouseId" filterable placeholder="请选择盘点仓库" style="width:100%" >
                <el-option  v-for="item in wareHouseDatas" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24">
            <el-form-item label="盘点类型:" prop="checkTypeId">
              <el-select  v-model="form.checkTypeId" filterable placeholder="请选择盘点类型" style="width:100%"  >
                <el-option  v-for="item in checkTypeDicts" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="库存金额:"  >
              <el-input v-model="form.sumStockAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="盘点金额:"  >
              <el-input v-model="form.sumCheckAmount" disabled />
            </el-form-item>
          </el-col>
          <el-col :md="6" :sm="24" >
            <el-form-item label="差异金额:"  >
              <el-input v-model="form.sumDiffAmount"   disabled/>
            </el-form-item>
          </el-col>
          <el-col :md="24" :sm="24" >
            <el-form-item label="备注:"  >
              <el-input :rows="2"
                  clearable
                  type="textarea"
                  :maxlength="200"
                  v-model="form.remark"
                  placeholder="请输入备注说明" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-card  style="margin-top: 10px">
        <div slot="header" class="clearfix" style="display: flex;justify-content:space-between;" >
          <div style="width: 50%;" >产品列表</div>
          <div style="width: 50%;display: flex;justify-content:end;" >
            <div style="width: 30%;color:var(--color-primary)" > 
                <el-button icon="el-icon-plus" style="width: 100%;" @click="OpenProductList"  >选择产品 </el-button>
              </div>
          </div>
        </div> 
        <el-table :data="form.items" ref="items"  :border="true" style="width: 100%"  :height="tableHeight" :full-height="tableFullHeight" >
          <el-table-column type="index" width="50" align="center" label="序号"  fixed='left' />
          <el-table-column label="产品编号" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productCode }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="产品名称" width="150"  align="center">
              <template slot-scope="{ row }">
                <el-form-item label-width="10" style="margin-bottom:0;" >
                  <span>{{ row.productName }}</span>
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="规格" align="center" width="100" >
            <template slot-scope="{ row }">
              <span>{{ row.spc }}</span>
            </template>
          </el-table-column>
          <el-table-column label="单位" align="center" width="100">
              <template slot-scope="{ row }">
                  <span>{{ row.unitDesc }}</span>
              </template>
          </el-table-column>
          <el-table-column label="实际库存" align="center" width="100">
              <template slot-scope="{ row }">
                <span>{{ row.stockQty }}</span>
                  <!-- <el-input  v-model="row.stockQty"  disabled /> -->
              </template>
          </el-table-column>
          <el-table-column label="盘点数量" align="center" width="100">
            <template slot-scope="{ row ,$index}">
              <el-form-item label-width="10" style="margin-bottom:0;" :prop="'items.'+ $index+'.checkQty'" :rules="itemRules.qty" >
                <el-input  v-model="row.checkQty"  placeholder="请输入数量" @change="setAmount(row,$index)"  @keyup.native="row.checkQty = row.checkQty.replace(/[^\d.]/g,'');
                  row.checkQty = row.checkQty.replace(/\.{2,}/g,'.');
                  row.checkQty = row.checkQty.replace(/^\./g,'');
                  row.checkQty = row.checkQty.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                  row.checkQty = row.checkQty.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column label="差异数量" align="center" width="100">
            <template slot-scope="{ row }">
              <span>{{ row.diffQty }}</span>
            </template>
          </el-table-column>
          <el-table-column label="成本单价(元)" align="center" width="150">
              <template slot-scope="{ row }">
                <!-- <span>{{ row.costPrice }}</span> -->
                <el-form-item label-width="10" style="margin-bottom:0;"  >
                  <el-input  v-model="row.costPrice"   prefix-icon="el-icon-_rmb" />
                </el-form-item>
              </template>
          </el-table-column>
          <el-table-column label="库存金额" align="center" width="120">
            <template slot-scope="{ row }">
              <span>{{ row.stockAmount }}</span>
              <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-input  v-model="row.stockAmount"  prefix-icon="el-icon-_rmb" disabled />
              </el-form-item> -->
            </template>
          </el-table-column>
          <el-table-column label="盘点金额" align="center" width="120">
            <template slot-scope="{ row }">
              <span>{{ row.checkAmount }}</span>
              <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-input  v-model="row.checkAmount"  prefix-icon="el-icon-_rmb" disabled />
              </el-form-item> -->
            </template>
          </el-table-column>
          <el-table-column label="差异金额" align="center" width="120">
            <template slot-scope="{ row }">
              <span>{{ row.diffAmount }}</span>
              <!-- <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-input  v-model="row.diffAmount"  prefix-icon="el-icon-_rmb" disabled />
              </el-form-item> -->
            </template>
          </el-table-column>
          <!-- <el-table-column label="供应商" width="150"  align="center">
            <template slot-scope="{ row }">
              <el-form-item label-width="10" style="margin-bottom:0;" >
                <el-select  filterable disabled v-model="row.supplierId" class="ele-fluid" >
                  <el-option v-for="item in supplierDatas" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column label="行备注" align="center" width="250">
            <template slot-scope="{ row }">
                <el-input  v-model="row.remarks" placeholder="请输入行备注" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" :resizable="false" v-if="this.btnIndex!=3" fixed='right'>
            <template slot-scope="{ row , $index}">
              <span class="ele-action">
                <el-link  icon="el-icon-delete" type="danger"   :underline="false" @click="remove(row, $index)" >删除</el-link>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
      <el-card shadow="never"> </el-card>
      <!-- 底部工具栏 -->
      <div class="ele-bottom-tool">
        <div  class="ele-text-danger">
          <i class="el-icon-circle-close"></i>
          <span>ss</span>
        </div>
        <div class="ele-bottom-tool-actions">
          <el-button type="primary" >
            提交
          </el-button>
        </div>
      </div>
    </el-form>
    <!-- <div slot="footer">
      <el-button type="primary" v-show="this.btnIndex!=3 && form.status!=5"  :loading="loading"  @click="save" >
        挂单
      </el-button>
      <el-button type="warning" v-show="this.btnIndex!=3 && form.status!=5" :loading="loading" @click="audit">
        审核
      </el-button>
      <el-button type="danger" v-show="form.status==5"  @click="unAudit"   >
        反审核
      </el-button>
      <el-button @click="handleClose" >关闭</el-button>
    </div> -->
     <!-- 编辑弹窗 -->
     <purChooseList :data="current" :visible.sync="showProductList"  @callback="reloadItemList"/>
    </ele-modal>
  </template>
  <script>
   
   import purChooseList from './purchoose-list.vue';
   import { getUser } from '@/utils/user-util';
   import upload from "@/components/UpLoad/index.js";
   import { GetAllAccount } from '@/api/usermanager/accountmanager';
   import { GetAllWarehouse } from '@/api/basicdatamanager/warehousemanager';
   import { QueryAllChildDictViewByCode } from '@/api/systemmanager/dictmanager';
   import { GetAllBSupplier } from '@/api/basicdatamanager/supplier';
   import { AddCheckorder, UpdateCheckorder,QueryCheckorderById,AuitCheckorder,AnitCheckorder } from '@/api/inventory/checkorder';


    export default {
      name: 'CheckOrderEdit',
      props: {
        // 弹窗是否打开
        visible: Boolean,
        // 修改回显的数据
        data: Object,
        // 按钮索引
        btnIndex:String,
      },
      mixins: [upload],
      components: {purChooseList},
      data() {
        return {
          fixedHeight:true,
          // 表单数据
          form: {createUser:'',createDate:''},
          // 表单验证规则
          rules: {
            wareHouseId: [{required: true,message: '请选择盘点仓库',trigger: 'blur'}],
            checkTypeId: [{required: true,message: '请选择盘点类型',trigger: 'blur'}],
            // supplierId: [{required: true,message: '请选择供应商',trigger: 'blur'}],
            // contractNumber: [{required: true,message: '请输入合同号',trigger: 'blur'}],
          },
          itemRules: {
            qty: [{required: true,message: '请输入数量',trigger: 'blur'}],
          },
          current:null,
          isShow:false,
          // 提交状态
          loading: false,
          // 是否是修改
          isUpdate: false,
          showProductList:false,
          defaultDate:new Date(),
          checkTypeDicts:[],
          accountDatas:[],
          supplierDatas:[],
          wareHouseDatas:[],
        };
      },
      computed: {
        // 表格高度
        tableHeight() {

          var fh = this.fixedHeight ? 'calc(100vh - 380px)' : void 0;
          return fh;
        },
        // 表格全屏时高度
        tableFullHeight() {
          var fh =  this.fixedHeight ? 'calc(100vh - 280px)' : null;
          return fh;
        },
      },
      //初始化数据
      mounted(){
        this.initData();
      },
      methods: {

        /* 初始化数据 */
        initData(){

          GetAllAccount().then((res)=>{
            this.accountDatas = [];
            this.accountDatas = res;
          });

          GetAllWarehouse().then((res)=>{
            this.wareHouseDatas = [];
            this.wareHouseDatas = res;
          });

          GetAllBSupplier().then((res)=>{
            this.supplierDatas = [];
            this.supplierDatas = res;
          });

          QueryAllChildDictViewByCode(this.Constant.C_PDLX).then((data)=>{
            this.checkTypeDicts = [];
            this.checkTypeDicts = data;
          });
        },

        save() {
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}

            this.loading = true;
            const saveOrUpdate = this.isUpdate ? UpdateCheckorder : AddCheckorder;
            saveOrUpdate(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        /* 审核入库单 */
        audit(){
          //校验必填信息
          this.$refs['form'].validate((valid) => {
            if (!valid) {return false;}


            if(this.form.items==null || this.form.items==undefined || this.form.items.length==0){
              this.$message.info('产品列表不能为空');
              return;
            }

            this.loading = true;
            AuitCheckorder(this.form)
              .then((msg) => {
                this.loading = false;
                this.$message.success(msg);
                this.updateVisible(false);
                //回调父组件方法
                this.$emit('done');
              })
              .catch((e) => {
                this.loading = false;
                this.$message.error(e.message);
              });
          });
        },

        unAudit(){
          this.loading = true;
          AnitCheckorder(this.form.id)
            .then((msg) => {
              this.loading = false;
              this.$message.success(msg);
              this.updateVisible(false);
              //回调父组件方法
              this.$emit('done');
            })
            .catch((e) => {
              this.loading = false;
              this.$message.error(e.message);
            });
        },

        setData(id){
          QueryCheckorderById(id)
            .then((res) => {
              this.form = res; 
               
          });
        },

        OpenProductList(){
          if(this.form.wareHouseId){
            this.showProductList =true;
            this.current = this.form;
          }else{
            this.$message.info("请选择盘点仓库")
          }
        },

        reloadItemList(orderData){

          this.form.items = [];
          orderData.map((item)=>{
            this.form.items.push({
              checkId:this.form.id,
              stockQty:item.stockQty,
              checkQty:item.stockQty,
              diffQty:0,
              checkAmount:(item.costPrice * item.stockQty).toFixed(4),
              diffAmount:0,
              stockAmount:(item.costPrice * item.stockQty).toFixed(4),
              stockId:item.id,
              costPrice:item.costPrice,
              purSharePrice:item.purSharePrice,
              inSharePrice:item.inSharePrice,
              billDetailId:item.billDetailId,
              stockItemId:item.stockItemId,
              unitId:item.unitId,
              productId:item.productId,
              productCode:item.productCode,
              productName:item.productName,
              spc:item.spc,
              unitDesc:item.unitDesc,
              supplierId:item.supplierId,
            })
          });

          this.$nextTick(() => {
            this.$refs.items.doLayout();
          });

          this.setPurAmountTotal();
        },

        //设置金额
        setAmount(row,index){

          this.$refs.items.data[index].diffQty = row.checkQty -row.stockQty

          if(row.costPrice && row.checkQty){
              let cq = parseFloat(row.checkQty);
              let cp = parseFloat(row.costPrice);
              this.$refs.items.data[index].checkAmount = (cp * cq).toFixed(2);
          }

          if(row.costPrice && row.diffQty){
              let dq = parseFloat(row.diffQty);
              let cp = parseFloat(row.costPrice);
              this.$refs.items.data[index].diffAmount = (cp * dq).toFixed(2);
          }

          this.setPurAmountTotal();
        },


        //设置入库金额
        setPurAmountTotal(){
          
          if(this.form.items!=null && this.form.items!=undefined && this.form.items.length>0){

            let ssa = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.stockAmount) },0);
            let sca = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.checkAmount) },0);
            let sda = this.form.items.reduce((pre,cur)=> { return parseFloat(pre)  + parseFloat(cur.diffAmount) },0);

            this.$set(this.form,'sumCheckAmount',sca.toFixed(2))
            this.$set(this.form,'sumStockAmount',ssa.toFixed(2))
            this.$set(this.form,'sumDiffAmount',sda.toFixed(2))
          }
        },

        /* 删除 */
        remove(_row, index) {
          this.form.items.splice(index, 1);
          this.setPurAmountTotal();
        },
     
        /* 更新visible */
        updateVisible(value) {
          //更新父组件中的visible的值
          this.$emit('update:visible', value);
        },

        handleClose() {
          this.$emit('update:visible', false);
        },
    },
     
      /* 监听visible属性变化 */
      watch: {
        visible(visible) {
         
          if (visible) {
            if (this.data && this.data.id) {
              //赋值this.form
              this.setData(this.data.id);
              this.isUpdate = this.data.id !=null && this.data.id !=undefined;
            } else {
              this.form={};
              this.isUpdate = false;

              let currentUser = getUser();
              this.$set(this.form,'createDate',this.defaultDate);
              this.$set(this.form,'createUser',currentUser.accountId);
            }
          } else {
              this.$refs['form'].clearValidate();
              this.form = {};
              let currentUser = getUser();
              this.$set(this.form,'createDate',this.defaultDate);
              this.$set(this.form,'createUser',currentUser.accountId);
          }
        }
      }
    };
  </script>
  <style lang='scss' scoped>
   .hangs_two {
    width: 70%;
    color: chocolate;
    cursor: pointer;
    .text {
      text-decoration: underline;
      margin-right: 4px;
    }
    .iconfont {
      margin-right: 4px;
    }
  }
</style>